package cn.wangqi.personal.controller;

import cn.wangqi.personal.common.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by admin on 2017/9/23.
 */
@Controller
public class IndexController extends BaseController{

    @RequestMapping("index.html")
    public String index(HttpServletRequest request) {
        try {
            return "index";
        } catch (Exception e) {
            e.printStackTrace();
            return "index";
        }
    }
    @RequestMapping(value = "/login.html")
    @ResponseBody
    public String doLogin(HttpServletRequest request, String userName ,String password, Boolean rememberMe,Model model) {
        String msg = "";
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        if(rememberMe){
            token.setRememberMe(true);
        }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return this.buildSuccessResponse();
        } catch (IncorrectCredentialsException e) {
            msg = e.getMessage();
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
        } catch (LockedAccountException e) {
            msg = e.getMessage();
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
        } catch (UnknownAccountException e) {
            msg = e.getMessage();
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
        }
        return this.buildErrorResponse(msg);
    }
    @RequestMapping(value = "/logout.html")
    @ResponseBody
    public String logout(HttpServletRequest request, Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return this.buildSuccessResponse();
    }

}
